import { obj_int, uJob, uReal, obj_str, d_sort, cline, for_obj } from 'sui';

const reload = (hDone, setMain, mod="re_pair") => {
    uReal(hDone, "pair/load",
        {
            line: cline(),
            k: mod,
        },
        r => {
            const ret = [];

            for_obj(r, (tsn, pair) => {
                let tmp = [];

                for_obj(pair, (k, v) => tmp.push(v));

                ret.push({
                    sn: tsn,
                    pnum: tmp.length,
                    sub: tmp,
                });
            });

            d_sort(ret, "sn");
            ret.forEach((d, i) => d["index"] = i + 1);

            setMain(ret);
        }, e => setMain(null));
};

const load_tech = (setList) => {
    uJob(null, "away/count", { line: cline() },
        r => {
            const ret = [];
            const set = new Set();

            r.forEach(d => {
                const tech = obj_str(d, "sn");
                if (!tech) {
                    return;
                }

                if (!set.has(tech)) {
                    ret.push({ sn: tech, name: tech });
                    set.add(tech);
                }
            });

            setList(ret);
        },
        e => setList(null));
};

const reload_count = (fnDone, setMain, setNum) => {
    uJob(fnDone, "away/count",
        {
            line: cline(),
        },
        r => {
            d_sort(r, "sn");

            let n = 0;

            r.forEach((d, i) => {
                d["index"] = i + 1;
                n += obj_int(d, "num");
            });

            setMain(r);
            setNum(n);
        }, e => setMain(null));
};

export {reload_count, load_tech, reload};
